#import "ValueSelectorView.h"

/**
 * A ValueSelectorView is an object representing a generic temporary
 * view for selecting an entry from a list of values.
 *
 * @author      James Lin
 * @version     1.1.5
 * @since       1.1.3
 */
@implementation ValueSelectorView

@synthesize cellText;
@synthesize cellValues;
@synthesize cellSelected;

/**
 * Initialize the value selector view.
 *
 * @param valueIndentifier  a unique identifier for this value selector view
 * @param values            a dictionary of values from which to select
 */
- (id)initWithIdentifier:(NSUInteger)valueIdentifier values:(NSDictionary*)values {
	if (self = [super init]) {
		// Set the unique identifier
		identifier = valueIdentifier;
		
		// Extract the values and value display text from the given dictionary
		self.cellValues = [[values allKeys] sortedArrayUsingSelector:@selector(compare:)];
		self.cellText = [values objectsForKeys:self.cellValues notFoundMarker:@""];
		self.cellSelected = [NSMutableArray array];
		
		// Create the table view to contain the value entries
		self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 
																		  VIEW_WIDTH, 
																		  VIEW_HEIGHT) 
														 style:UITableViewStylePlain];
		self.tableView.backgroundColor = [UIColor lightGrayColor];
		self.tableView.separatorColor = [UIColor whiteColor];
		self.tableView.tableFooterView = [[[UIView alloc] 
											  initWithFrame:CGRectMake(0, 0, 1, 60)] autorelease];
		[self.tableView setRowHeight:DEFAULT_CELL_HEIGHT];
	}
	
	
	return self;
}

/**
 * Set the delegate handling events from this view.
 *
 * @param theDelegate  the delegate handling events from this view
 * @see                ValueSelectorDelegate
 */
- (void)setDelegate:(id<ValueSelectorDelegate>)theDelegate {
	delegate = theDelegate;
}

/**
 * Display the table listing of values in a new view.
 *
 * Pushes this view onto the navigation controller stack of the parent
 * view. Upon tapping the back button, the view is automatically 
 * popped off the top of the navigation stack.
 *
 * @param title          title of the temporary view
 * @param navController  the navigation controller of the parent view
 * @param selected       the value that is to be preselected
 */
- (void)displayViewWithTitle:(NSString*)title 
			   navController:(UINavigationController*)navController 
			   selectedValue:(id)selected {
	self.navigationItem.title = title;
	parentNav = navController;
	
	// Set the preselected value
	if (selected) {
		[self.cellSelected removeAllObjects];
		[self.cellSelected addObject:selected];
	}
	
	// Display the table of values
	[parentNav pushViewController:self animated:YES];
}

/**
 * Get the number of rows in the table view.
 */
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
	return [cellValues count];
}

/**
 * Populate a table view cell in the table view with content.
 */
- (UITableViewCell*)tableView:(UITableView*)tableView 
		cellForRowAtIndexPath:(NSIndexPath*)indexPath {
	static NSString* CellIdentifier = @"ValueSelectorCell";
	UITableViewCell* cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if (cell == nil) {
		// Create an empty reusable cell for performance sake
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
									   reuseIdentifier:CellIdentifier] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
	}
	
	// Refresh the label content of the cell
	cell.textLabel.text = [cellText objectAtIndex:indexPath.row];
	cell.textLabel.font = [UIFont boldSystemFontOfSize:13.5];
	
	// Check if the value is selected
	if ([cellSelected containsObject:[cellValues objectAtIndex:indexPath.row]]) {
		cell.accessoryType = UITableViewCellAccessoryCheckmark;
	} else {
		cell.accessoryType = UITableViewCellAccessoryNone;
	}
	
	return cell;
}

/**
 * Handle a table row entry selection.
 */
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
	// Search for the selected entr(ies)
	if (![cellSelected containsObject:[cellValues objectAtIndex:indexPath.row]]) {
		[cellSelected removeAllObjects];
		[cellSelected addObject:[cellValues objectAtIndex:indexPath.row]];
		[delegate valueSelected:[cellValues objectAtIndex:indexPath.row] 
			 selectorIdentifier:identifier];
	}
	
	[self.tableView reloadData];
	[parentNav popViewControllerAnimated:YES];
}

/**
 * Deallocate the value selector view.
 */
- (void)dealloc {
	delegate = nil;
	[cellSelected release];
	cellSelected = nil;
	[cellText release];
	cellText = nil;
	[cellValues release];
	cellValues = nil;
	parentNav = nil;
    [super dealloc];
}

@end